package com.mediacloud.app.newsmodule.view

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.text.TextUtils
import android.text.TextUtils.isEmpty
import android.util.AttributeSet
import android.util.DisplayMetrics
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.eventTrack.TXReportManager
import com.mediacloud.app.assembly.util.StringUtils
import com.mediacloud.app.assembly.views.TimeLineRelativeLayout
import com.mediacloud.app.model.news.ArticleItem
import com.mediacloud.app.model.news.kt.TypeX
import com.mediacloud.app.newsmodule.R
import com.mediacloud.app.newsmodule.adaptor.basenews.BaseStyleViewHolder
import com.mediacloud.app.newsmodule.adaptor.groupimage.GroupPhotoDefaultStyleHolder
import com.mediacloud.app.newsmodule.adaptor.imgtxt.ImageTxtListViewDefaultStyleHolder
import com.mediacloud.app.newsmodule.adaptor.video.live.LiveNewsDefaultStyleHolder
import com.mediacloud.app.newsmodule.adaptor.video.vod.VirtualNewsDefaultStyleHolder
import com.mediacloud.app.newsmodule.fragment.NotIntrestEvent
import com.mediacloud.app.newsmodule.utils.LoginUtils
import com.mediacloud.app.newsmodule.utils.SBShareUtils
import com.mediacloud.app.share.model.ShareGridItem
import com.mediacloud.app.share.view.SharePopGridWindow
import com.mediacloud.app.user.model.UserInfo
import com.utils.ActivityScanner
import com.utils.DeviceUtils
import org.greenrobot.eventbus.EventBus
import xyz.doikki.videoplayer.util.PlayerUtils.getWindowManager

class NewInfoView(context: Context?, attrs: AttributeSet?) : LinearLayout(context, attrs),
    SharePopGridWindow.OnGridItemClickListener {
    var color = Color.parseColor("#999999")
    var space = resources.getDimensionPixelSize(R.dimen.dimen7)

    //    var typeTV = TextView(context)
//    val lineView = View(context)
//
//    var sourceTV = TextView(context)
//    var dateTV = TextView(context)
//    var hitTv = TextView(context)
//    var interactTV = TextView(context)
//    var feedback = ImageView(context)
    var typeTV: TextView
    var lineView: View

    var addressTv: TextView
    var sourceTV: TextView
    var dateTV: TextView
    var hitTv: TextView
    var interactTV: TextView
    var feedback: ImageView
    var adTV: ImageView
    var childrenWidth = 0
    var sharePopWindow: PosterShareGridPop? = null
    var shareGridDataUtil: SBShareUtils? = null
    var articleItem: ArticleItem? = null

    init {
        val view = LayoutInflater.from(context).inflate(R.layout.layout_infoview, this)
        typeTV = view.findViewById(R.id.typeTV)
        adTV = view.findViewById(R.id.adTV)
        lineView = view.findViewById(R.id.lineView)
        addressTv = view.findViewById(R.id.text_address)
        sourceTV = view.findViewById(R.id.sourceTV)
        dateTV = view.findViewById(R.id.dateTV)
        hitTv = view.findViewById(R.id.hitTv)
        interactTV = view.findViewById(R.id.interactTV)
        feedback = view.findViewById(R.id.feedback)
        orientation = HORIZONTAL
        shareGridDataUtil = SBShareUtils()

    }

    @SuppressLint("SetTextI18n")
    fun handleArticle(rootView: View, article: ArticleItem, holder: BaseStyleViewHolder? = null) {
        //Log.e("holder", "$holder")
        if (DeviceUtils.isCus(context) && !article.isComponent) feedback.visibility = View.VISIBLE
        else feedback.visibility = View.GONE
        articleItem = article

        //跟谭老板确认过，统一不要这个标识了
        typeTV?.visibility = View.GONE
        lineView?.visibility = View.GONE

        if (article.type == TypeX.NEWS.NEWS_AD) adTV.visibility =
            View.VISIBLE else adTV.visibility = View.GONE
        var timeLine = false

        if (rootView is TimeLineRelativeLayout) {
            rootView.tempTimeTV = dateTV
            rootView.articleId = "${article.id}"
            rootView.publishDate = article.publishdate_format
            if (rootView.haveChecked) {
                timeLine = rootView.appfacFlag
                if (timeLine) {
                    rootView.publishDate = null
                    rootView.titleText?.text = article.publishdate_format
                }
            }
        }
        addressTv.visibility = View.GONE
        article.spider_user?.let {
            if (!isEmpty(it.ipAddress)) {
                addressTv.visibility = View.VISIBLE
                addressTv.text = it.ipAddress
            }
        }

        article.mShowSwitch?.let {
            //来源
            if (it.allowShowSource) {
                sourceTV.visibility = View.VISIBLE
                if (article.type == TypeX.NEWS.NEWS_AD) {
                    sourceTV.text = article?.prop1
                } else {
                 /*   if (isEmpty(article?.spider_user?.userNickName))
                        if (!isEmpty(article?.authorNickName)) {
                            sourceTV.text = article?.authorNickName
                        } else {
                            sourceTV.text = context.getResources().getString(R.string.app_name)
                        }
                    else sourceTV.text = article?.spider_user?.userNickName*/
                    if (isEmpty(article?.referName))
                        sourceTV.text = context.resources.getString(R.string.app_name)
                    else sourceTV.text = article?.referName
                }

            } else {
                sourceTV.visibility = View.GONE
            }
            //发布时间
            if (it.allowShowPublishDate && article.publishdate_format != null && article.publishdate_format.isNotBlank()) {
                dateTV.visibility = View.VISIBLE

                //老谭说新版本只要这个日期了
                dateTV.text = article.publishdate_format
            } else {
                dateTV.visibility = View.GONE
            }
            //专题  隐藏阅读数和评论数    林茂生说 type为8是专题类型 不显示数互动数量  云效bug   16669
            //浏览
            if (it.allowShowHitCount && article.showreadingcountflag == 1 && article.getType() != TypeX.NEWS.TOPIC) {
                hitTv.visibility = View.VISIBLE
                var hit = "${StringUtils.toTenThousand(article.hitCount)}"

                hitTv.text = hit
            } else {
                hitTv.visibility = View.GONE
            }
            //评论
            if ((it.allowShowComment && article.isComment == "1" && article.getType() != TypeX.NEWS.TOPIC)
                || it.allowShowInteractionCount
            ) {
                if (it.allowShowInteractionCount) {
                    interactTV.visibility = View.VISIBLE
                    interactTV.text = "${StringUtils.toTenThousand(article.interactionCount)} 互动"
                } else {
                    interactTV.visibility = View.VISIBLE
                    interactTV.text = "${StringUtils.toTenThousand(article.commentCount)} 评"
                }
            } else {
                interactTV.visibility = View.GONE
//                interactTV.visibility = View.VISIBLE
                interactTV.text = "${StringUtils.toTenThousand(article.commentCount)} 评"
            }

        }

        if (holder is LiveNewsDefaultStyleHolder) {
            sourceTV.maxEms = 4
            val measuretype = typeTV.paint.measureText(typeTV.text.toString())
            val measureInteract = interactTV.paint.measureText(interactTV.text.toString())
            val measureHit = hitTv.paint.measureText(hitTv.text.toString())
            val metric = DisplayMetrics()
            getWindowManager(context).defaultDisplay.getRealMetrics(metric)
            val allWidth = metric.widthPixels.toFloat()
            //图片固定宽114,item左右边距24，控件之间的space
            dateTV.layoutParams.width =
                (allWidth - dp2px(context, 114 + 24) - measuretype - measureInteract -
                        measureHit - 5 * space).toInt()
        }
        if (holder is GroupPhotoDefaultStyleHolder
            || holder is VirtualNewsDefaultStyleHolder
            || holder is ImageTxtListViewDefaultStyleHolder
        ) sourceTV.maxEms = 8
        feedback.setOnClickListener { view ->
            sharePopWindow = PosterShareGridPop(feedback.context)
            sharePopWindow?.setonFuncItemClick(this)
            sharePopWindow?.let {
                if (it.isShowing) return@setOnClickListener
                shareGridDataUtil?.funcGridData?.clear()
                shareGridDataUtil?.funcGridData?.add(
                    ShareGridItem(
                        SBShareUtils.sharereport,
                        R.drawable.share_jb,
                        SharePopGridWindow.FuncType
                    )
                )
                shareGridDataUtil?.funcGridData?.add(
                    ShareGridItem(
                        SBShareUtils.NotInterested,
                        R.drawable.share_nes_feedback,
                        SharePopGridWindow.FuncType
                    )
                )
                sharePopWindow?.setFuncGridAdaptorData(shareGridDataUtil?.funcGridData)
                if (view.context is Activity) {
                    it.show(view.context as Activity)
                } else {
                    val activity: Activity? = ActivityScanner.findActivity(view)
                    activity?.let {
                        sharePopWindow?.show(activity)
                    }
                }
            }
        }
    }

    fun dp2px(context: Context, dpValue: Int): Float {
        val scale = context.resources.displayMetrics.density
        return dpValue * scale + 0.5f
    }

    override fun setShareOnItemClick(p0: Int) {

    }

    override fun setFuncOnitemClick(position: Int) {
        sharePopWindow?.dismiss()
        val userInfo = UserInfo.getUserInfo(context)
        shareGridDataUtil?.let {
            val label = it.funcGridData[position].label //功能按钮
            when (label) {
                SBShareUtils.sharereport -> {//举报
                    if (!userInfo.isLogin()) {
                        LoginUtils.request_source = "举报"
                        LoginUtils.invokeLogin(context)
                        return
                    }
                    val intent = Intent()
                    intent.setClassName(
                        context,
                        "com.mediacloud.app.appfactory.report.ReportReasonActivity"
                    )
                    intent.putExtra("ArticleItem", articleItem)
                    context.startActivity(intent)
                }

                SBShareUtils.NotInterested -> {//不感兴趣
                    EventBus.getDefault().post(NotIntrestEvent(articleItem?.id))
                    TXReportManager.getInstance().not_interested(articleItem)
                }

                else -> {
                }


            }

        }
    }
}